import * as chartjsExt from "../../js/chartjs-ext.js";

export function createChart(domCanvas) {
    if (domCanvas == null)
        return;
    let chartConfig = {
        type: 'line',
        data: {
            labels: [0, 1],
            datasets: [{
                label: 'X',
                data: [NaN, NaN],
                borderWidth: 1,
                borderColor: '#00A',
                backgroundColor: '#00A'
            }, {
                label: 'Y',
                data: [NaN, NaN],
                borderWidth: 1,
                borderColor: '#0A0',
                backgroundColor: '#0A0'
            }, {
                label: 'Z',
                data: [NaN, NaN],
                borderWidth: 1,
                borderColor: '#A00',
                backgroundColor: '#A00'
            }]
        },
        options: {
            maintainAspectRatio: false,
            interaction: {
                // Overrides the global setting
                mode: 'index',
                intersect: false
            },
            scales: {
                x: {
                    type: "linear",
                    ticks: {
                        callback: function (value, index, ticks) {
                            let v = value;
                            if (!Number.isFinite(v))
                                return;
                            return chartjsExt.toStopWatchTimeDetailString(v);
                        }
                    }
                },
                y: {
                    beginAtZero: true
                }
            },
            plugins: {
                tooltip: {
                    callbacks: {
                        title: function (context) {
                            return chartjsExt.toStopWatchTimeDetailString(context[0].parsed.x);
                        }
                    }
                }
            }
        }
    };
    let chart = new Chart(domCanvas, chartConfig);
    domCanvas.chart = chart;
    return chart;
}

export function setChartData(domCanvas, ts, xs, ys, zs) {
    let chart = domCanvas?.chart;
    if (chart == null)
        return;
    chart.data.labels = ts;
    chart.data.datasets[0].data = xs;
    chart.data.datasets[1].data = ys;
    chart.data.datasets[2].data = zs;
    if (ts.length > 0) {
        chart.options.scales.x.min = ts[0];
        chart.options.scales.x.max = ts[ts.length-1];
    }
    else {
        chart.options.scales.x.min = 0;
        chart.options.scales.x.max = 1;
    }
}

export function setChartVRange(domCanvas, vmin, vmax) {
    let chart = domCanvas?.chart;
    if (chart == null)
        return;
    chart.options.scales.y.min = vmin;
    chart.options.scales.y.max = vmax;
} 